#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>

void mysys(char *command)
{
    char *p = command;
    char *argv[256];
    int num = 0;
    int i = 0;
    int j = 0;

    while (*p)
    {
        if (*p == ' ')
        {
            j = 0;
            i++;
            num++;
        }
        else
        {
            if (j == 0)
            {
                argv[i] = (char *)malloc(sizeof(char) * 256);
            }
            argv[i][j] = *p;
            j++;
        }
        p++;
    }
    i++;
    argv[i] = NULL;


    if(strcmp(argv[0], "exit") == 0)
    {
        exit(0);
    }
    if(strcmp(argv[0],"cd") == 0)
    {
        if(chdir(argv[1])){//chdir
            printf("myselous:cd:%s:no such directory\n",argv[1]);
        }
        return;
    }

    if(strcmp(argv[0], "pwd") == 0)
    {
        char buf[200];
        printf("%s\n",getcwd(buf,sizeof(buf)));//getcwd
        return;
    }

    pid_t pid;
    pid = fork();
    if (pid == 0)
    {

        int dd = execvp(argv[0], argv);
        if (dd < 0)
            perror(argv[0]);
        puts("after exec");
    }

    wait(NULL);
}

int main()
{
    int fd[2];
    char buf[100];
    int count;
    while (1)
    {
        printf("> ");
        fflush(stdout);
        count = read(1, buf, sizeof(buf));
        buf[count - 1] = 0;
        mysys(buf);
    }
    return 0;
}
